// game/snake.go

package game

import (
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"image/color"
)

type Snake struct {
	segments  []Segment
	direction Direction
}

type Segment struct {
	x, y int
}

type Direction int

const (
	Up Direction = iota
	Down
	Left
	Right
)

func NewSnake() *Snake {
	snake := &Snake{
		segments:  []Segment{{3, 1}, {2, 1}, {1, 1}},
		direction: Right,
	}
	return snake
}

// game/snake.go

func (s *Snake) Eat() {
	// 获取蛇的尾部
	tail := s.segments[len(s.segments)-1]
	// 创建一个新的段，位置与尾部相同
	newSegment := Segment{tail.x, tail.y}
	// 将新的段添加到蛇的尾部
	s.segments = append(s.segments, newSegment)
}
func (s *Snake) SetDirection(newDirection Direction) {
	// 设置蛇的移动方向
	s.direction = newDirection
}
func (s *Snake) Move() {
	// 保存原始头部坐标
	oldHead := s.segments[0]
	// 根据当前方向移动头部
	switch s.direction {
	case Up:
		s.segments[0].y--
	case Down:
		s.segments[0].y++
	case Left:
		s.segments[0].x--
	case Right:
		s.segments[0].x++
	}
	// 移动蛇的身体，每一节移到前一节的位置
	for i := 1; i < len(s.segments); i++ {
		oldX := s.segments[i].x
		oldY := s.segments[i].y
		s.segments[i].x = oldHead.x
		s.segments[i].y = oldHead.y
		oldHead.x = oldX
		oldHead.y = oldY
	}
}
func (s *Snake) Move1() {
	if ebiten.IsKeyPressed(ebiten.KeyArrowUp) {
		s.SetDirection(Up)
	} else if ebiten.IsKeyPressed(ebiten.KeyArrowDown) {
		s.SetDirection(Down)
	} else if ebiten.IsKeyPressed(ebiten.KeyArrowLeft) {
		s.SetDirection(Left)
	} else if ebiten.IsKeyPressed(ebiten.KeyArrowRight) {
		s.SetDirection(Right)
	}
}
func (s *Snake) Draw(screen *ebiten.Image) {
	green := color.RGBA{0, 255, 0, 255}

	for _, segment := range s.segments {
		x, y := segment.x*gridSize, segment.y*gridSize
		ebitenutil.DrawRect(screen, float64(x), float64(y), gridSize, gridSize, green)

	}

}
